<template>
  <div class="app-container">
    <div class="left baseBoderShadow bgWhite baseBorderRadius">
      <div class="seachBox">
        <el-input v-model.trim="seachName_jg" placeholder="请输入机构名称" clearable @keyup.enter.native="search_jg">
          <i slot="suffix" class="el-icon-search" style="line-height: 36px; width: 30px;cursor: pointer;" @click="search_jg" />
        </el-input>
      </div>
      <div id="greenTree" class="scroBox" style=" height: 624px;">
        <el-scrollbar :wrap-style="[{ 'height': '100%' }]">
          <el-tree ref="tree" :data="treeDate" :default-expanded-keys="keysArr" :current-node-key="currentNodekey" :props="defaultProps" node-key="id" highlight-current @node-click="zzjgNodeClick">
            <template slot-scope="{ node, data }">
              <span :title="data.zzjg_name" class="overSpan">{{ data.zzjg_name }}</span>
            </template>
          </el-tree>
        </el-scrollbar>
      </div>
    </div>
    <div class="right">
      <!-- 查询和其他操作 -->
      <div class="filter-container">

      &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
        <br>
        <el-date-picker
          v-model="downData.gmtStart"
          type="datetime"
          style="width: 200px"
          class="filter-item"
          default-time="00:00:00"
          placeholder="选择开始日期"
        />
        至
        <el-date-picker
          v-model="downData.gmtEnd"
          type="datetime"
          style="width: 200px"
          class="filter-item"
          default-time="00:00:00"
          placeholder="选择结束日期"
        />
        <el-button
          v-permission="['operation:order:list']"
          class="filter-item"
          type="primary"
          icon="el-icon-search"
          @click="handleFilter"
        >查找</el-button>
        <el-button :loading="downloadLoading" class="filter-item" type="primary" icon="el-icon-download" @click="downExcelBtn">导出</el-button>
        <el-button :loading="downloadLoading" class="filter-item" type="primary" icon="el-icon-download" @click="downExcelBtnWx">导出微信对帐单</el-button>
      </div>

      <!-- 查询结果 -->
      <el-table
        v-loading="listLoading"
        height="635px"
        :data="list"
        element-loading-text="正在查询中。。。"
      >

        <el-table-column align="center" width="250" label="所属店铺" prop="zzjgName" />
        <el-table-column align="center" width="120" label="成交金额" prop="inPrice">
        </el-table-column>
        <el-table-column align="center" width="120" label="结算费率" prop="sc">
          <template slot-scope="scope">
              {{ (scope.row.sc*100).toFixed(2) }}%
          </template>
        </el-table-column>
        <el-table-column align="center" width="120" label="手续费" prop="scPriceWeiXin"/>
        <el-table-column align="center" width="120" label="实际收入" prop="scPriceWeiXin">
          <template slot-scope="scope">
            {{ scope.row.inPrice-scope.row.scPriceWeiXin }}
          </template>
        </el-table-column>
        <el-table-column align="center" width="110" label="退款金额" prop="outPrice">
        </el-table-column>

        <el-table-column align="center"  label="日期" prop="createDate">
          <template slot-scope="scope">{{ scope.row.createDate | formatDateNYR }}</template>
        </el-table-column>

      </el-table>
    </div>
  </div>
</template>

<script>
import { listOrderByDayNew, listOrderByDayNewWx,shipOrderNew, refundOrderNew, detailOrderNew, editAdminMonoNew, getExcelStatisticsNew } from "@/api/order";
import Pagination from "@/components/Pagination";
import {formatDate,formatDateNYR} from "@/filters"; // Secondary package based on el-pagination





export default {
  name: "Order",
  components: { Pagination },
  data() {
    return {
      userZzjg: [],
      defaultProps: {
        label: "zzjg_name",
        value: "id",
        children: "children"
      },
      currentNodekey: "",
      keysArr: [],
      treeDate: [],
      currentId: "",
      seachName_jg: "",
      excelData: {
        barcode: undefined,
        name: undefined,
        specifications: undefined,
        unit: undefined,
        num: undefined,
        address: undefined
      },
      excelDataList: [],
      downData: {
        status: "",
        gmtStart: undefined,
        gmtEnd: undefined
      },
      list: undefined,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        id: undefined,
        name: undefined
      },
      orderDialogVisible: false,
      orderDetail: {},
      refundForm: {
        orderNo: undefined,
        type: 0
      },
      refundDialogVisible: false,
      refundSubmiting: false,
      adminMonoDialogVisible: false,
      downloadLoading: false,
      shipForm: {
        orderNo: undefined,
        shipCode: "NONE",
        shipNo: undefined
      },
      shipDialogVisible: false,
      shipSubmiting: false,
      refundRules: {
        orderNo: [
          { required: true, message: "请使用非IE浏览器重试", trigger: "blur" }
        ],
        type: [
          { required: true, message: "请选择退货类型", trigger: "blur" }
        ]
      },
      shipRules: {
        shipCode: [
          { required: true, message: "请选择物流类型", trigger: "blur" }
        ],
        orderNo: [
          { required: true, message: "请使用非IE浏览器重试", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getDepartmentList();
  },
  methods: {
    /**
       * @name zzjgnodeClick
       * @description 点击树形结构
       * @author wqy
       * @date 2019-10-31 10:32:34
       */
    zzjgNodeClick(data, currentNode, node) {
      this.currentId = data.id;
      this.currentName = data.zzjg_name;
      this.parentId = data.parent_id;

      this.isEmpty = false; // 全局搜索，输入框当前是否为空
      this.byJgFlag = true; // 当前为组织机构的获取的列表
      // 清空多选框
      this.seachName = "";
      this.getList();// 根据组织机构查询用户
    },
    async getDepartmentList() {
      const data = {
        searchName: this.seachName_jg
      };
      const res = await this.$store.dispatch(
        "qxgl-yhzzgl/getDepartmentList",
        data
      );
      this.treeDate = res.data;
      const id = res.data[0].id;
      this.currentName = res.data[0].zzjg_name;
      this.currentId = id;
      this.firstId = id; // 记录最高级别的id
      // 设置默认选中并高亮显示
      if (this.userZzjg.length !== 0) {
        this.keysArr = this.userZzjg;
        this.currentId = this.userZzjg[0];
        this.currentNodekey = this.userZzjg[0];
      } else {
        this.currentNodekey = id;
        this.keysArr.push(id);
      }
      this.$nextTick(() => {
        const tree = this.$refs.tree;
        tree.setCurrentKey(this.currentId); // 指定选中的节点
        // getCurrentNode 获取当前节点的信息
        const currentNode = this.$refs.tree.getCurrentNode();
        this.currentName = currentNode.zzjg_name;
        this.parentId = currentNode.parent_id;
        // 根据组织机构查询类目
        this.getList();
      });
    },
    async search_jg() {
      const data = {
        searchName: this.seachName_jg
      };
      const res = await this.$store.dispatch(
        "qxgl-yhzzgl/getDepartmentList",
        data
      );
      this.treeDate = res.data;
      // 清空右侧
      // this.checkAll = false;
      // this.isIndeterminate = false;
      this.checkList = [];
      // this.currentPage = 1;
    },
    getList() {
      this.listLoading = true;
      this.listQuery.zzjgId = this.currentId;
      console.log("listquery", this.listQuery);
      if (this.downData.gmtStart) {
        this.listQuery["gmtStart"] = this.downData.gmtStart.getTime();
      }
      if (this.downData.gmtEnd) {
        this.listQuery["gmtEnd"] = this.downData.gmtEnd.getTime();
      }
      listOrderByDayNew(this.listQuery)
        .then(response => {
          console.log("response", response);
          //TODO 111
          this.list = response.data;
          this.total = response.data.total;
          this.listLoading = false;
        })
        .catch(() => {
          this.list = [];
          this.total = 0;
          this.listLoading = false;
        });
    },
    handleFilter() {
      this.listQuery.page = 1;
      this.getList();
    },
    handleDetail(row) {
      console.log("rwo", row);
      detailOrderNew(row.id).then(response => {
        this.orderDetail = response.data;
      });
      this.orderDialogVisible = true;
    },
    // 选择条件下载
    downExcelBtn() {
      this.downloadLoading = true;
      this.listQuery.zzjgId = this.currentId;
      console.log("listquery", this.listQuery);
      if (this.downData.gmtStart) {
        this.listQuery["gmtStart"] = this.downData.gmtStart.getTime();
      }
      if (this.downData.gmtEnd) {
        this.listQuery["gmtEnd"] = this.downData.gmtEnd.getTime();
      }

      listOrderByDayNew(this.listQuery)
        .then(response => {
          if (response.data == null) {
            this.$notify.error({
              title: "失败",
              message: "没有信息可以打印"
            });
          }
          console.log("response", response);
          var data = response.data;
          debugger
          data.forEach(item=>{
            //item.createDate = item.createDate.Format('yyyy-MM-dd')
            item.acturePrice = item.inPrice - item.scPriceWeiXin
            item.sc = (item.sc*100).toFixed(2)+"%"
          })
          this.handleDownload(data, { start: this.listQuery["gmtStart"], end: this.listQuery["gmtEnd"] });
          this.excelDataList = [];
          this.downloadLoading = false;
        })
        .catch((e) => {
          this.downloadLoading = false;
          this.$notify.error({
            title: "失败",
            message: e.message
          });
        });
    },
    // 选择条件下载
    downExcelBtnWx() {
      this.downloadLoading = true;
      this.listQuery.zzjgId = this.currentId;
      console.log("listquery", this.listQuery);
      if (this.downData.gmtStart) {
        this.listQuery["gmtStart"] = this.downData.gmtStart.getTime();
      }
      listOrderByDayNewWx(this.listQuery)
        .then(response => {
          if (response.data == null) {
            this.$notify.error({
              title: "失败",
              message: "没有信息可以打印"
            });
          }
          console.log("response", response);
          var data = response.data.billInfoList;
          debugger
          data.forEach(item=>{
            //item.createDate = item.createDate.Format('yyyy-MM-dd')
            item.acturePrice = item.totalAmount - item.poundage
          })
          this.handleDownloadWX(data, response.data,{ start: this.listQuery["gmtStart"], end: this.listQuery["gmtEnd"] });
          this.excelDataList = [];
          this.downloadLoading = false;
        })
        .catch((e) => {
          this.downloadLoading = false;
          this.$notify.error({
            title: "失败",
            message: e.message
          });
        });
    },
    handleDownload(data, options = {}) {
        import("@/vendor/Export2Excel").then(excel => {
          const tHeader = [
            "所属店铺",
            "成交金额",
            "结算费率",
            "手续费",
            "实际收入",
            "退款金额",
            "日期"
          ];
          const filterVal = [
            "zzjgName",
            "inPrice",
            "sc",
            "scPriceWeiXin",
            "acturePrice",
            "outPrice",
            "createDate"

          ];
          if (options.start == null) {
            options.start = new Date("1990-01-01").getTime();
          }
          if (options.end == null) {
            options.end = new Date().getTime();
          }
          excel.export_json_to_excel2(tHeader, data, filterVal, this.currentName + ":订单汇总:" + new Date(options.start).Format("yyyy-MM-dd hh:mm:ss") + "至" + new Date(options.end).Format("yyyy-MM-dd hh:mm:ss"));
        });
    },
    handleDownloadWX(data,totalData, options = {}) {
      import("@/vendor/Export2Excel").then(excel => {
        const tHeader = [
          "交易时间",
          "成交金额",
          "结算费率",
          "手续费",
          "实收",
          "交易状态"

        ];
        const filterVal = [
          "tradeTime",
          "totalAmount",
          "poundageRate",   //手续费率
          "poundage",       //手续费
          "acturePrice",      //实际收入
          "tradeState"



        ];
        if (options.start == null) {
          options.start = new Date("1990-01-01").getTime();
        }
        if (options.end == null) {
          options.end = new Date().getTime();
        }
        let {totalAmount,totalFee,totalPoundageFee,totalRecord} = totalData;
        let total1 = {tradeTime:'当日总计',totalAmount:"成交金额",poundage:"总手续费",acturePrice:"当时总实收",poundageRate:"交易笔数"};
        let total = {tradeTime:new Date(options.start).Format("yyyy-MM-dd"),totalAmount:totalAmount,poundage:totalPoundageFee,poundageRate:totalRecord,acturePrice:totalAmount-totalPoundageFee};
        data.unshift(total)
        data.unshift(total1)
        excel.export_json_to_excel2(tHeader, data, filterVal, this.currentName + ":订单汇总:" + new Date(options.start).Format("yyyy-MM-dd hh:mm:ss") + "至" + new Date(options.end).Format("yyyy-MM-dd hh:mm:ss"));
      });
    }
  }
};
</script>
<style>
  .el-table .danger-row {
    background: rgb(201, 143, 143);
  }

  .el-table .warning-row {
    background: rgb(197, 175, 142);
  }

  .el-table .success-row {
    background: rgb(166, 202, 149);
  }
  .right{
    padding-top: 15px;
  }
</style>
